class LoginController < ApplicationController

  # if the user is trying to login, then skip the :check_login filter specified by application.rb
  skip_before_filter :check_login
  
  def authenticate
    session[:user] = nil

    unless params[:username].blank? || params[:password].blank?
      @username = Username.find_by_username params[:username]      

      unless @username.nil?
        if @username.username == "shrimpadmin"
          session[:user] = @username.user
        else
          logger.info "Found username: " << @username.inspect
          @user = @username.user

          case @username.authentication_type
          when AuthenticationType.find_by_name("ecommons")
            session[:user] = @user if authenticate_ecommons
          when AuthenticationType.find_by_name("local")
            session[:user] = @user if authenticate_locally
          end
        end
      else
        logger.info "Could not find user with username: \"#{params[:username]}\""
      end
    end

    if session[:user].nil?
      flash[:error] = 'Login failed!  Username or password was incorrect.'
      redirect_to :controller => "login" 
    else
      logger.info "Successfully authenticated user: " << @user.inspect
      flash[:notice] = 'Login successful!  Welcome, ' + session[:user].fullname + '!'
      requested = session[:requested_path]
      requested ||= root_path
      redirect_to requested
    end
  end

  def logout
    session[:user] = nil
    flash[:notice] = "You have successfully logged out of SHRIMP."
    redirect_to :controller => "login"
  end

  ECOMMONS_AUTH_URL = "https://www.countway.harvard.edu/ws/ecommonsauth.cgi"

  private
  def authenticate_ecommons
    client = HTTPClient.new
    body = {'user' => params[:username], 'pass' => params[:password]}
    response = client.post_content(ECOMMONS_AUTH_URL, body)

    logger.info "Response from eCommons authentication is: \"" << response << "\""

    unless response.empty? || response.downcase == "null"
      results = response.split
      if(results.size >= 3)
        return true
      end
    end

    return false
  end
  
  def authenticate_locally
    sha256 = Digest::SHA256.new
    return @username.password == sha256.hexdigest(params[:password] + @username.password_salt)
  end

end
